package com.brainhealth.customer.service.impl;

import com.brainhealth.common.constant.NumberConstants;
import com.brainhealth.common.core.domain.TreeSelect;
import com.brainhealth.common.enums.GoodsType;
import com.brainhealth.common.enums.PropertyStatusEnum;
import com.brainhealth.common.enums.YNEnum;
import com.brainhealth.common.utils.DateUtils;
import com.brainhealth.customer.domain.Customer;
import com.brainhealth.customer.domain.RoomUserProperty;
import com.brainhealth.customer.domain.ScoreMallGoodsCategory;
import com.brainhealth.customer.domain.vo.FirstCategoryPropertyVO;
import com.brainhealth.customer.domain.vo.SecondaryCategoryProperty;
import com.brainhealth.customer.domain.vo.ThirdCategoryProperty;
import com.brainhealth.customer.service.IRoomUserPropertyService;
import com.brainhealth.customer.service.IScoreMallGoodsCategoryService;
import com.brainhealth.customer.service.IWarehouseService;
import com.brainhealth.utils.CommonUtils;
import io.jsonwebtoken.lang.Assert;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 仓库服务
 *
 * @author wll
 */
@Service
public class WarehouseServiceImpl implements IWarehouseService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public static final String ALL_DESC = "全部";

    @Autowired
    IScoreMallGoodsCategoryService scoreMallGoodsCategoryService;

    @Autowired
    IRoomUserPropertyService roomUserPropertyService;

    /**
     * 道具分类ID
     */
    public static final Long PROPERTY_CATEGORY_ROOT_ID = 0l;

    @Override
    public List<FirstCategoryPropertyVO> getPropertyList(HttpServletRequest request) {
        long ts = DateUtils.getTimeMillis();
        try {
            Customer customer = CommonUtils.getCustomerByRequest(request);

            ScoreMallGoodsCategory scoreMallGoodsCategory = new ScoreMallGoodsCategory();
            scoreMallGoodsCategory.setParentCategoryId(PROPERTY_CATEGORY_ROOT_ID);
            List<TreeSelect> treeSelectList = scoreMallGoodsCategoryService.getScoreMallGoodsCategoryTree();
            int size = CollectionUtils.isEmpty(treeSelectList) ? 0 : treeSelectList.size();
            logger.info("ts{}查询到商品分类信息{}条", ts, size);
            List<FirstCategoryPropertyVO> firstCategoryPropertyVOList = getFirstCategoryPropertyVOList(customer.getCustomerId(), treeSelectList);
            int propertySize = CollectionUtils.isEmpty(treeSelectList) ? 0 : treeSelectList.size();
            logger.info("ts{}商品信息{}", ts, propertySize);

            return firstCategoryPropertyVOList;
        } catch (Exception e) {
            logger.error("ts{}查询我的货仓异常", ts, e);
            return null;
        }

    }

    @Override
    public List<FirstCategoryPropertyVO> getUsedPropertyList(HttpServletRequest request) {
        long ts = DateUtils.getTimeMillis();
        try {
            Customer customer = CommonUtils.getCustomerByRequest(request);

            ScoreMallGoodsCategory scoreMallGoodsCategory = new ScoreMallGoodsCategory();
            scoreMallGoodsCategory.setParentCategoryId(PROPERTY_CATEGORY_ROOT_ID);
            List<TreeSelect> treeSelectList = scoreMallGoodsCategoryService.getScoreMallGoodsCategoryTree();
            int size = CollectionUtils.isEmpty(treeSelectList) ? 0 : treeSelectList.size();
            logger.info("ts{}查询到商品分类信息{}条", ts, size);
            List<FirstCategoryPropertyVO> firstCategoryPropertyVOList = getFirstCategoryPropertyList(customer.getCustomerId(), treeSelectList);
            int propertySize = CollectionUtils.isEmpty(treeSelectList) ? 0 : treeSelectList.size();
            logger.info("ts{}商品信息{}", ts, propertySize);

            return firstCategoryPropertyVOList;
        } catch (Exception e) {
            logger.error("ts{}查询我的货仓异常", ts, e);
            return null;
        }
    }

    /**
     * 查询1级分类道具 -> 在商品分类中查询
     * 查询2级分类道具 -> 在商品分类中查询
     * 查询3级分类道具 -> 在用户道具中查询
     *
     * @param customerId
     * @param scoreMallGoodsCategoryTree
     * @return
     */
    private List<FirstCategoryPropertyVO> getFirstCategoryPropertyVOList(Long customerId, List<TreeSelect> scoreMallGoodsCategoryTree) {
        if (CollectionUtils.isEmpty(scoreMallGoodsCategoryTree)) {
            return null;
        }
        List<FirstCategoryPropertyVO> firstCategoryPropertyVOList = new ArrayList<>();
        FirstCategoryPropertyVO firstCategoryPropertyVO = null;
        Integer firstShowFlag = YNEnum.YES.getCode();
        for (TreeSelect treeSelect : scoreMallGoodsCategoryTree) {
            firstCategoryPropertyVO = new FirstCategoryPropertyVO();
            firstCategoryPropertyVO.setFirstCategoryId(treeSelect.getId());
            firstCategoryPropertyVO.setFirstCategoryName(treeSelect.getLabel());
            firstCategoryPropertyVO.setFirstShowFlag(firstShowFlag);
            firstShowFlag = YNEnum.NO.getCode();
            List<SecondaryCategoryProperty> secondaryCategoryPropertyList = new ArrayList<>();
            SecondaryCategoryProperty secondaryCategoryProperty = null;
            List<TreeSelect> firstChildren = treeSelect.getChildren();
            List<ThirdCategoryProperty> allThirdCategoryPropertyList = null;
            if (CollectionUtils.isNotEmpty(firstChildren)) {
                allThirdCategoryPropertyList = new LinkedList<>();
                secondaryCategoryProperty = new SecondaryCategoryProperty();
                secondaryCategoryProperty.setSecondaryCategoryId(Long.valueOf(NumberConstants.NEGATIVE_ONE));
                secondaryCategoryProperty.setSecondaryCategoryName(ALL_DESC);
                secondaryCategoryProperty.setThirdCategoryPropertyList(allThirdCategoryPropertyList);
                Integer secondaryShowFlag = YNEnum.YES.getCode();
                secondaryCategoryProperty.setSecondaryShowFlag(secondaryShowFlag);
                secondaryShowFlag = YNEnum.NO.getCode();
                secondaryCategoryPropertyList.add(0, secondaryCategoryProperty);
                for (TreeSelect child : firstChildren) {
                    secondaryCategoryProperty = new SecondaryCategoryProperty();
                    secondaryCategoryProperty.setSecondaryCategoryId(child.getId());
                    secondaryCategoryProperty.setSecondaryCategoryName(child.getLabel());

                    RoomUserProperty roomUserProperty = new RoomUserProperty();
                    roomUserProperty.setCustomerId(customerId);
                    roomUserProperty.setYn(YNEnum.NO.getCode());
                    roomUserProperty.setGoodsCategoryId(child.getId().intValue());
                    //roomUserProperty.setGoodsType(GoodsType.AIPackage.getCode());
                    List<RoomUserProperty> roomUserPropertyList = roomUserPropertyService.getRoomUserPropertyList(roomUserProperty);
                    List<ThirdCategoryProperty> thirdCategoryPropertyList = getThirdCategoryPropertyList(roomUserPropertyList);
                    if (CollectionUtils.isNotEmpty(thirdCategoryPropertyList)) {
                        allThirdCategoryPropertyList.addAll(thirdCategoryPropertyList);
                    }
                    secondaryCategoryProperty.setThirdCategoryPropertyList(thirdCategoryPropertyList);
                    secondaryCategoryProperty.setSecondaryShowFlag(secondaryShowFlag);
                    secondaryCategoryPropertyList.add(secondaryCategoryProperty);
                }
                firstCategoryPropertyVO.setSecondaryCategoryPropertyList(secondaryCategoryPropertyList);
            }
            firstCategoryPropertyVOList.add(firstCategoryPropertyVO);
        }
        return firstCategoryPropertyVOList;
    }

    /**
     * 查询1级分类道具 -> 在商品分类中查询
     * 查询2级分类道具 -> 在商品分类中查询
     * 查询3级分类道具 -> 在用户道具中查询
     *
     * @param customerId
     * @param scoreMallGoodsCategoryTree
     * @return
     */
    private List<FirstCategoryPropertyVO> getFirstCategoryPropertyList(Long customerId, List<TreeSelect> scoreMallGoodsCategoryTree) {
        if (CollectionUtils.isEmpty(scoreMallGoodsCategoryTree)) {
            return null;
        }
        List<FirstCategoryPropertyVO> firstCategoryPropertyVOList = new ArrayList<>();
        FirstCategoryPropertyVO firstCategoryPropertyVO = null;
        for (TreeSelect treeSelect : scoreMallGoodsCategoryTree) {
            firstCategoryPropertyVO = new FirstCategoryPropertyVO();
            firstCategoryPropertyVO.setFirstCategoryId(treeSelect.getId());
            firstCategoryPropertyVO.setFirstCategoryName(treeSelect.getLabel());
            List<SecondaryCategoryProperty> secondaryCategoryPropertyList = new ArrayList<>();
            SecondaryCategoryProperty secondaryCategoryProperty = null;
            List<TreeSelect> firstChildren = treeSelect.getChildren();
            if (CollectionUtils.isNotEmpty(firstChildren)) {
                for (TreeSelect child : firstChildren) {
                    secondaryCategoryProperty = new SecondaryCategoryProperty();
                    secondaryCategoryProperty.setSecondaryCategoryId(child.getId());
                    secondaryCategoryProperty.setSecondaryCategoryName(child.getLabel());

                    RoomUserProperty roomUserProperty = new RoomUserProperty();
                    roomUserProperty.setCustomerId(customerId);
                    roomUserProperty.setYn(YNEnum.NO.getCode());
                    roomUserProperty.setGoodsCategoryId(child.getId().intValue());
                    List<RoomUserProperty> roomUserPropertyList = roomUserPropertyService.getRoomUserPropertyList(roomUserProperty);
                    List<ThirdCategoryProperty> thirdCategoryPropertyList = getThirdCategoryPropertyList(roomUserPropertyList);
                    secondaryCategoryProperty.setThirdCategoryPropertyList(thirdCategoryPropertyList);
                    secondaryCategoryPropertyList.add(secondaryCategoryProperty);
                }
                firstCategoryPropertyVO.setSecondaryCategoryPropertyList(secondaryCategoryPropertyList);
            }
            firstCategoryPropertyVOList.add(firstCategoryPropertyVO);
        }
        return firstCategoryPropertyVOList;
    }


    private List<ThirdCategoryProperty> getThirdCategoryPropertyList(List<RoomUserProperty> roomUserPropertyList) {
        if (CollectionUtils.isEmpty(roomUserPropertyList)) {
            return null;
        }
        List<ThirdCategoryProperty> thirdCategoryPropertyList = new ArrayList<>();
        ThirdCategoryProperty thirdCategoryProperty = null;
        RoomUserProperty userProperty = roomUserPropertyList.get(0);
        Integer goodsStatus = userProperty.getGoodsType();

        if (GoodsType.AIPackage.getCode() == goodsStatus) {
            roomUserPropertyList = roomUserPropertyList.stream().filter(item -> PropertyStatusEnum.NOT_USED.getCode() == item.getGoodsStatus()).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(roomUserPropertyList)){
                return null;
            }
            Long categoryId = null == userProperty.getGoodsCategoryId() ? Long.valueOf(NumberConstants.ZERO) : Long.valueOf(userProperty.getGoodsCategoryId());

            RoomUserProperty roomUserProperty = roomUserPropertyList.get(0);
            thirdCategoryProperty = new ThirdCategoryProperty();
            thirdCategoryProperty.setGoodsShortName(roomUserProperty.getGoodsShortName());
            thirdCategoryProperty.setGoodsSmallImg(roomUserProperty.getGoodsSmallImg());
            thirdCategoryProperty.setGoodsImg(roomUserProperty.getGoodsImg());
            thirdCategoryProperty.setGoodsBigImg(roomUserProperty.getGoodsBigImg());
            int thirdCategorySize = roomUserPropertyList.size();
            thirdCategoryProperty.setGoodsStatus(PropertyStatusEnum.NOT_USED.getCode());
            thirdCategoryProperty.setGoodsAmount(thirdCategorySize);
            thirdCategoryProperty.setSecondaryCategoryId(categoryId);
            thirdCategoryProperty.setLayer(roomUserProperty.getLayer());
            thirdCategoryPropertyList.add(thirdCategoryProperty);

            return thirdCategoryPropertyList;
        }

        for (RoomUserProperty roomUserProperty : roomUserPropertyList) {
            Long categoryId = null == roomUserProperty.getGoodsCategoryId() ? Long.valueOf(NumberConstants.ZERO) : Long.valueOf(roomUserProperty.getGoodsCategoryId());
            thirdCategoryProperty = new ThirdCategoryProperty();
            thirdCategoryProperty.setPropertyId(roomUserProperty.getPropertyId());
            thirdCategoryProperty.setGoodsShortName(roomUserProperty.getGoodsShortName());
            thirdCategoryProperty.setGoodsSmallImg(roomUserProperty.getGoodsSmallImg());
            thirdCategoryProperty.setGoodsImg(roomUserProperty.getGoodsImg());
            thirdCategoryProperty.setGoodsBigImg(roomUserProperty.getGoodsBigImg());
            thirdCategoryProperty.setGoodsStatus(roomUserProperty.getGoodsStatus());
            thirdCategoryProperty.setSecondaryCategoryId(categoryId);
            thirdCategoryProperty.setLayer(roomUserProperty.getLayer());
            thirdCategoryPropertyList.add(thirdCategoryProperty);
        }

        return thirdCategoryPropertyList;
    }


    @Override
    public Integer useProperty(HttpServletRequest request, String strPropertyId) {
        long ts = DateUtils.getTimeMillis();
        try {
            Assert.notNull(strPropertyId);
            Long propertyId = Long.valueOf(strPropertyId);
            logger.info("ts{}装饰房间开始，道具ID{}", ts, propertyId);
            Customer customer = CommonUtils.getCustomerByRequest(request);
            RoomUserProperty roomUserProperty = new RoomUserProperty();
            roomUserProperty.setCustomerId(customer.getCustomerId());
            roomUserProperty.setPropertyId(propertyId);
            roomUserProperty.setYn(YNEnum.NO.getCode());
            List<RoomUserProperty> roomUserPropertyList = roomUserPropertyService.selectRoomUserPropertyList(roomUserProperty);
            if (CollectionUtils.isEmpty(roomUserPropertyList)) {
                logger.info("ts{}, 用户{}道具{}不存在", ts, customer.getCustomerId(), propertyId);
                return YNEnum.NO.getCode();
            }
            RoomUserProperty userProperty = roomUserPropertyList.get(0);
            if (null != userProperty.getGoodsStatus()
                    && PropertyStatusEnum.USED.getCode() == userProperty.getGoodsStatus()) {
                logger.info("ts{}, 用户{}道具{}已使用", ts, customer.getCustomerId(), propertyId);
                return YNEnum.NO.getCode();
            }
            Integer goodsCategoryId = userProperty.getGoodsCategoryId();
            RoomUserProperty property = new RoomUserProperty();
            property.setCustomerId(customer.getCustomerId());
            property.setGoodsCategoryId(goodsCategoryId);
            property.setGoodsStatus(PropertyStatusEnum.USED.getCode());
            List<RoomUserProperty> propertyList = roomUserPropertyService.selectRoomUserPropertyList(property);
            if (CollectionUtils.isNotEmpty(propertyList)) {
                List<Long> idList = propertyList.stream().map(item -> item.getId()).collect(Collectors.toList());
                property.setIdList(idList);
                property.setGoodsStatus(PropertyStatusEnum.NOT_USED.getCode());
                int updateResult = roomUserPropertyService.updateUserProperty(property);
                logger.info("ts{}, 用户{}道具分类{}更新状态为未使用，结果{}", ts, customer.getCustomerId(), goodsCategoryId, updateResult);
            }
            userProperty.setGoodsStatus(PropertyStatusEnum.USED.getCode());
            int updateResult = roomUserPropertyService.updateRoomUserProperty(userProperty);
            logger.info("ts{}装饰房间结束，结果{}", ts, updateResult);
            if (updateResult > 0) {
                return YNEnum.YES.getCode();
            }
            return YNEnum.NO.getCode();
        } catch (Exception e) {
            logger.error("ts{}装饰房间异常", ts, e);
            return null;
        }
    }

    @Override
    public Integer isUseProperty(HttpServletRequest request) {
        long ts = DateUtils.getTimeMillis();
        try {
            logger.info("ts{}是否装饰过房间开始", ts);
            Customer customer = CommonUtils.getCustomerByRequest(request);
            RoomUserProperty roomUserProperty = new RoomUserProperty();
            roomUserProperty.setCustomerId(customer.getCustomerId());
            roomUserProperty.setYn(YNEnum.NO.getCode());
            List<RoomUserProperty> roomUserPropertyList = roomUserPropertyService.selectRoomUserPropertyList(roomUserProperty);
            if (CollectionUtils.isNotEmpty(roomUserPropertyList)) {
                boolean matchResult = roomUserPropertyList.stream().allMatch(item -> null != item.getGoodsStatus() && PropertyStatusEnum.NOT_USED.getCode() == item.getGoodsStatus());
                logger.info("ts{}, 用户{}道具数目{}是否装饰过房间结果{}，", ts, customer.getCustomerId(), roomUserPropertyList.size(), matchResult);
                return matchResult ? YNEnum.NO.getCode() : YNEnum.YES.getCode();
            }
            logger.info("ts{}, 用户{}没有装饰房间道具", ts, customer.getCustomerId());
            return YNEnum.NO.getCode();
        } catch (Exception e) {
            logger.error("ts{}是否装饰过房间异常", ts, e);
            return null;
        }
    }

    @Override
    public Integer resetProperty(HttpServletRequest request) {
        long ts = DateUtils.getTimeMillis();
        try {
            logger.info("ts{}重新布置开始", ts);
            Customer customer = CommonUtils.getCustomerByRequest(request);
            Date now = DateUtils.getNowDate();
            RoomUserProperty roomUserProperty = new RoomUserProperty();
            roomUserProperty.setCustomerId(customer.getCustomerId());
            roomUserProperty.setGoodsStatus(PropertyStatusEnum.USED.getCode());
            List<RoomUserProperty> roomUserPropertyList = roomUserPropertyService.selectRoomUserPropertyList(roomUserProperty);
            if (CollectionUtils.isNotEmpty(roomUserPropertyList)) {
                List<Long> idList = roomUserPropertyList.stream().map(item -> item.getId()).collect(Collectors.toList());
                roomUserProperty = new RoomUserProperty();
                roomUserProperty.setIdList(idList);
                roomUserProperty.setGoodsStatus(PropertyStatusEnum.NOT_USED.getCode());
                Long customerId = customer.getCustomerId();
                String strCustomerId = null == customerId ? "" : String.valueOf(customerId);
                roomUserProperty.setUpdateUser(strCustomerId);
                roomUserProperty.setUpdateTime(now);
                int updateResult = roomUserPropertyService.resetProperty(roomUserProperty);
                if (updateResult > 0) {
                    logger.info("ts{}重新布置结束，更新数据条数{}", ts, updateResult);
                    return YNEnum.YES.getCode();
                }
                return YNEnum.NO.getCode();
            }
            logger.info("ts{}重新布置，用户{}无使用中的道具", ts, customer.getCustomerId());
            return YNEnum.NO.getCode();
        } catch (Exception e) {
            logger.error("ts{}重新布置异常", ts, e);
            return null;
        }
    }
}
